package torrentfile

import (
	"BTClient/p2p"
	"bytes"
	"github.com/jackpal/bencode-go"
)

type singleTorrent struct {
	// `bencode:""`
	// tracker服务器的URL 字符串
	Announce string `bencode:"announce"`
	// 备用tracker服务器列表 列表
	// 发现 announce-list 后面跟了两个l(ll) announce-listll
	AnnounceList [][]string `bencode:"announce-list"`
	// 种子的创建时间 整数
	CreatDate int64 `bencode:"creation date"`
	// 备注 字符串
	Comment string `bencode:"comment"`
	// 创建者 字符串
	CreatedBy string     `bencode:"created by"`
	Info      singleInfo `bencode:"info"`
	// 包含一系列ip和相应端口的列表，是用于连接DHT初始node
	Nodes [][]interface{} `bencode:"nodes"`
	// 文件的默认编码
	Encoding string `bencode:"encoding"`
	// 备注的utf-8编码
	CommentUtf8 string `bencode:"comment.utf-8"`
}

// 单文件
type singleInfo struct {
	Pieces      string `bencode:"pieces"`
	PieceLength int    `bencode:"piece length"`
	Length      int    `bencode:"length"`
	Name        string `bencode:"name"`

	// 文件发布者
	Publisher string `bencode:"publisher,omitempty"`
	// 文件发布者的网址
	PublisherUrl string `bencode:"publisher-url,omitempty"`

	NameUtf8         string `bencode:"name.utf-8,omitempty"`
	PublisherUtf8    string `bencode:"publisher.utf-8,omitempty"`
	PublisherUrlUtf8 string `bencode:"publisher-url.utf-8,omitempty"`
	MD5Sum           string `bencode:"md5sum,omitempty"`
	Private          bool   `bencode:"private,omitempty"`
}

// 将pieces（以前是一个字符串)拆分为一片哈希（每个[20]byte).以便以后可以轻松访问各个哈希.
// 还计算了整个bencoded infodict（包含名称.大小和片段哈希的dict)的SHA-1哈希.
// 将其称为infohash.在与Tracker服务器和Peer设备对话时.它唯一地标识文件.

// fileParser 单文件解析
func (bto *singleTorrent) fileParser(file []byte) error {
	// 可以进行 反序列化 key value取值
	// fileMetaData, er := bencode.Decode(file)
	// if er != nil {
	// }
	//fmt.Println(fileMetaData)
	err := bencode.Unmarshal(bytes.NewReader(file), &bto)
	return err
}

func (bto *singleTorrent) toTorrentFile() (TorrentFile, error) {
	infoHash, err := hash(bto.Info)
	if err != nil {
		return TorrentFile{}, err
	}

	// 每个分片的 SHA-1 hash 长度是20 把他们从Pieces中切出来
	pieceHashes, err := splitPieceHashes(bto.Info.Pieces)
	if err != nil {
		return TorrentFile{}, err
	}

	tf := TorrentFile{
		Announce: bto.Announce,
		Torrent: p2p.Torrent{
			InfoHash:    infoHash,
			PieceHashes: pieceHashes,
			PieceLength: bto.Info.PieceLength,
			Length:      bto.Info.Length,
			Name:        bto.Info.Name,
		},
	}

	// 添加 备用节点
	tf.AnnounceList = []string{}
	for _, v := range bto.AnnounceList {
		tf.AnnounceList = append(tf.AnnounceList, v[0])
	}

	return tf, nil
}

func (bto *singleTorrent) writerFile() {}
